<script lang="ts" setup>
import { useStoreDict } from '@/store/modules/dict'
import { useGetOrderPage, useOrderAdd, useOrderDel } from '@fl/api/man-api/pricing-tool'
import { cloneDeep } from 'lodash-es'
import { nextTick, ref, toRefs } from 'vue'

import AddPricingModel from './add-pricing-model.vue'

const props = withDefaults(defineProps<{
    id?: number | string
    limit?: number
}>(), {
    limit: 20,
})

const { id, limit } = toRefs(props)
const { dicts } = useStoreDict()
const tableRef = ref()
const tableData = ref<any>([])
const show = ref(false)
const rowData = ref({})
const rowIdx = ref(0)

const cache = ref<any>([])

const params = computed(() => ({
    categoryId: id.value,
}))
const { data, isLoading, refetch } = useGetOrderPage(params)

watchEffect(() => {
    if (data.value) {
        tableData.value = cloneDeep(data.value)
        cache.value = cloneDeep(data.value)
    }
})

// 添加规格型号
function addItem({ $index, row }) {
    rowIdx.value = $index
    rowData.value = row
    show.value = true
}
// 保存规格型号
function onSuccess(val: any) {
    tableData.value[rowIdx.value].itemModels = val
}

const { mutate: mutateDel } = useOrderDel()
function doDel({ $index, row }) {
    ElMessageBox.confirm('该操作将永久删除，是否继续?', '提示', { type: 'warning' })
        .then(() => {
            if (row?.id) {
                mutateDel(row.id, {
                    onSuccess: () => {
                        ElMessage({ message: '操作成功', type: 'success' })
                    },
                })
            }
            else {
                ElMessage({ message: '操作成功', type: 'success' })
            }

            tableData.value.splice($index, 1)
        })
}

function doAdd() {
    const len = tableData.value.length
    if (len >= limit.value) {
        ElMessage.error(`最多添加${limit.value}条数据！`)
        return
    }

    let isNext = true
    // 校验上条数据 是否填写完整
    if (len) {
        const target = tableData.value[len - 1]
        if (/^\s*$/.test(target.itemName) || /^\s*$/.test(target.unit)) {
            isNext = false
        }
    }

    if (!isNext) {
        ElMessage.error(`请填写完整第${len}条数据`)
        return
    }

    const categoryId = Number(id.value)
    tableData.value.push({
        categoryId,
        itemModels: [],
        itemName: '',
        unit: tableData.value[0]?.unit ?? '',
    })

    if (tableData.value.length > 5) {
        nextTick(() => {
            tableRef.value.setScrollTop(len * 300)
        })
    }
}

const { mutate } = useOrderAdd()
function doSave(fn?: any) {
    const target = tableData.value
    if (!target.length) {
        ElMessage.error(`请添加清单！`)
        return
    }
    // 重复校验
    const noRepeat = new Set([...target.map((v: any) => v.itemName)])
    if (target.length !== noRepeat.size) {
        ElMessage.error(`存在重复材料名称`)
        return
    }

    const isEnpty = target.some((v: any) => !v.itemName || !v.unit)
    if (isEnpty) {
        ElMessage.error(`请填写完整再保存`)
        return
    }

    // 报价清单 统一单位校验
    const unit = tableData.value[0].unit
    const flag = tableData.value.some((v: any) => v.unit !== unit)
    if (flag) {
        ElMessage.error(`请保证计量单位一致`)
        return
    }

    mutate(tableData.value, {
        onSuccess: () => {
            refetch()
            ElMessage({ message: '操作成功', type: 'success' })
            if (fn)
                fn()
        },
    })
}

function unitChange(val: any) {
    tableData.value.forEach((v: any, index) => {
        if (index > 0) {
            v.unit = val
        }
    })
}

function getUnit({ row }) {
    const label = dicts.jc_zjgj_unit.find((v: any) => v.value === row.unit)?.label
    return label || row.unit || ''
}

// 检测是否存在未保存数据
function hasDraft() {
    return cache.value.length !== tableData.value.length || JSON.stringify(cache.value) !== JSON.stringify(tableData.value)
}

defineExpose({
    doSave,
    hasDraft,
})
</script>

<template>
    <div class="mb-20 c-#1d2129 font-600">
        清单列表
    </div>

    <el-table ref="tableRef"
              v-loading="isLoading"
              :data="tableData"
              stripe
              style="width: 100%"
              height="300"
    >
        <el-table-column label="序号"
                         type="index"
                         width="55"
        />

        <el-table-column label="材料名称"
                         width="280"
        >
            <template #header>
                <span><span class="mr-5 c-red">*</span>材料名称</span>
            </template>

            <template #default="scope">
                <el-input v-model="scope.row.itemName"
                          :maxlength="20"
                          type="text"
                          show-word-limit
                          placeholder="请输入"
                          clearable
                />
            </template>
        </el-table-column>

        <el-table-column label="计量单位"
                         width="120"
        >
            <template #header>
                <span><span class="mr-5 c-red">*</span>计量单位</span>
            </template>

            <template #default="scope">
                <el-select v-if="scope.$index === 0"
                           v-model="scope.row.unit"
                           @change="unitChange"
                >
                    <el-option v-for="item in dicts.jc_zjgj_unit"
                               :key="item.value"
                               :label="item.label"
                               :value="item.label"
                    />
                </el-select>

                <span v-else>{{ getUnit(scope) }}</span>
            </template>
        </el-table-column>

        <el-table-column label="规格型号">
            <template #default="scope">
                <div v-if="scope.row.itemModels?.length"
                     @click="addItem(scope)"
                >
                    <template v-for="item in scope.row.itemModels"
                              :key="item.id"
                    >
                        <el-tag v-if="item.isDeleted === 0"
                                class="mr-3"
                                ype="success"
                        >
                            {{ item.model }}
                        </el-tag>
                    </template>
                </div>
            </template>
        </el-table-column>

        <el-table-column label="操作"
                         width="150"
        >
            <template #default="scope">
                <el-button link
                           type="danger"
                           @click="addItem(scope)"
                >
                    添加规格
                </el-button>

                <el-button link
                           @click="doDel(scope)"
                >
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-button class="mt-20"
               type="primary"
               plain
               @click="doAdd"
    >
        + 添加清单
    </el-button>

    <AddPricingModel v-model="show"
                     :data="rowData"
                     @on-success="onSuccess"
    />
</template>
